<template>

  <a-row>
    <a-row>
      demo
      <a-tree-select
        v-model="value"
        style="width: 100%"
        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
        :tree-data="departTree"
        placeholder="Please select"
        :treeDefaultExpandedKeys="[departTree[0].key]"
      >
      </a-tree-select>
    </a-row>
    <a-card :body-style="{padding: '24px 32px'}" :bordered="false" :span="8">
      <a-col :span="5">
        <a-button @click="batchDel">
          批量删除
        </a-button>
        <a-dropdown :trigger="['click']" placement="bottomCenter" style="margin-left: 10px">
          <a-menu slot="overlay">
            <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
            <a-menu-item key="4" @click="cancelCheckALL">取消全选</a-menu-item>
            <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
            <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
          </a-menu>
          <a-button>
            树操作
            <a-icon type="down"/>
          </a-button>
        </a-dropdown>
        <a-alert type="info" showIcon style="margin-top: 5px">
          <div slot="message">
            <span>当前选择：{{ (checkDeptName || '') }} </span>
            <a style="margin-left: 10px;" @click="onClearSelected" v-if="checkDeptName">取消选择</a>
          </div>
        </a-alert>
        <a-input-search style="margin-bottom: 8px;margin-top: 5px" placeholder="请输入树" @change="onChange"/>
        <template>
          <div>
            <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
              <span style="user-select: none">
                <a-tree
                  v-if="departTree.length"
                  checkable
                  checkStrictly
                  @check="onCheck"
                  @expand="onExpand"
                  @rightClick="rightHandle"
                  :defaultExpandedKeys="defaultExpandedKeys"
                  :expandedKeys="expandedKeys"
                  :autoExpandParent="autoExpandParent"
                  v-model="checkedKeys"
                  @select="onSelect"
                  :selectedKeys="selectedKeys"
                  :treeData="departTree"
                /></span>
              <a-menu slot="overlay">
                <a-menu-item @click="handleAdd" key="1" v-wx-role="50501">添加</a-menu-item>
                <a-menu-item @click="handleDelete" key="2" v-wx-role="50504">删除</a-menu-item>
                <a-menu-item @click="closeDrop" key="3">取消</a-menu-item>
              </a-menu>
            </a-dropdown>
          </div>
        </template>

      </a-col>
      <a-col :span="19">
        <a-form-model
          ref="ruleForm"
          :model="selectDeptInfo"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-model-item
            label="树名称"
            prop="name"
            ref="name"
            :rules="$valid.required"
            :maxLength="50">
            <a-input v-model="selectDeptInfo.name" placeholder="请输入"/>
          </a-form-model-item>
          <a-form-model-item
            label="上级树"
            prop="parentId"
            :rules="$valid.required">
            <a-input v-model="selectDeptInfo.parentId" placeholder="请输入" type="hidden"/>
            <a-input-search
              placeholder="点击右侧按钮选择树"
              v-model="selectDeptInfo.parentName"
              onfocus="this.blur()"
              @search="departCodeSearch">
              <a-button slot="enterButton" icon="search">选择</a-button>
            </a-input-search>
          </a-form-model-item>
          <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button
              type="primary"
              @click="onSubmit"
              v-if="orgCategoryDisabled&&selectDeptInfo.id!=1">
              修改并保存
            </a-button>
            <a-button
              type="primary"
              @click="onSubmit"
              v-if="!orgCategoryDisabled">
              新增
            </a-button>
            <a-button style="margin-left: 10px;" @click="resetForm" v-if="selectDeptInfo.id!=1">
              重置
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </a-col>
      <depart-window ref="departCodeRef" @ok="departCodeOk" :multiple-flag="false"></depart-window>
    </a-card>
  </a-row>
</template>

<script>
import { PageView } from '@/layouts'
import departWindow from '../../../components/WxDepartChoose/DepartWindow'
import { deleteAction, getAction, postAction } from '@/api/manage'

let expandedKeySource = []
let selectList = []
let selectParentList = []
export default {
  name: 'DepartList',
  components: {
    PageView,
    departWindow
  },
  data () {
    return {
      value: undefined,
      url: {
        getDepartTree: '/system/ktree/tree',
        getDeptInfo: '/system/ktree/info',
        departSave: '/system/ktree/save',
        departDel: '/system/ktree/delete'
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      defaultExpandedKeys: [],
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      rightClickSelectedKey: '',
      rightClickSelectedValue: '',
      rightClickSelectedName: '',
      allTreeKeys: [],
      dropTrigger: '11',
      orgCategoryDisabled: false,
      selectDeptInfo: {
        parentId: undefined,
        parentName: undefined,
        areaCode: undefined,
        areaData: undefined,
        address: undefined,
        orgFlag: 0
      },
      checkDeptName: '',
      departTree: [],
      departListSys: []
    }
  },
  created () {
    this.initData(true)
  },
  mounted () {
  },
  watch: {
    selectedKeys (val) {
      this.$refs.ruleForm.resetFields()
    },
    value (value) {
      console.log(value)
    }
  },
  methods: {
    onSubmit () {
      this.$refs.ruleForm.validate(valid => {
        console.log(valid)
        if (valid) {
          postAction(this.url.departSave, this.selectDeptInfo).then(res => {
            this.checkDeptName = this.selectDeptInfo.name
            this.$message.success(res.content)
            this.initData(false)
          })
        } else {
          return false
        }
      })
    },
    // 获取用户对应树弹出框提交给返回的数据
    departCodeOk (formData) {
      const departCodeNames = []
      const departCodeKeys = []
      let departCodeNameString = ''
      for (let i = 0; i < formData.departIdList.length; i++) {
        departCodeKeys.push(formData.departIdList[i].key)
        departCodeNames.push(formData.departIdList[i].title)
        departCodeNameString = departCodeNames.join(',')
      }
      if (departCodeKeys.length > 0) {
        this.selectDeptInfo.parentId = departCodeKeys[0]
        this.selectDeptInfo.parentName = departCodeNameString
      }
    },
    // 搜索用户对应的归属树API
    departCodeSearch () {
      this.$refs.departCodeRef.add([this.selectDeptInfo.parentId])
    },
    // 重置表单
    resetForm () {
      this.selectDeptInfo.parentId = undefined
      this.selectDeptInfo.parentName = ''
      this.orgCategoryDisabled = false
      this.selectDeptInfo.id = undefined
      this.selectDeptInfo.areaCode = undefined
      this.selectDeptInfo.areaData = undefined
      this.checkDeptName = ''
      this.selectedKeys = []
      this.selectDeptInfo.address = ''
      this.$refs.ruleForm.resetFields()
    },
    // 批量删除
    batchDel: function () {
      if (!this.checkedKeys.checked || this.checkedKeys.checked.length <= 0) {
        this.$message.warning('请勾选一条记录！')
      } else {
        var ids = ''
        for (var a = 0; a < this.checkedKeys.checked.length; a++) {
          ids += this.checkedKeys.checked[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '确定要删除所选中的 ' + that.checkedKeys.checked.length + ' 条数据，以及子节点数据吗?',
          onOk: function () {
            deleteAction(that.url.departDel, { ids: ids }).then((res) => {
              that.$message.success(res.content)
              that.initData(false)
              that.resetForm()
            })
          }
        })
      }
    },
    handleIconChange (icon) {
      console.log('change Icon', icon)
    },
    // tree 展开
    onExpand (expandedK, expandedExtr) {
      this.expandedKeys = expandedK
    },
    // 清空选择
    onClearSelected () {
      this.resetForm()
    },
    // 触发onSelect事件时,为树树右侧的form表单赋值
    setValuesToForm (record) {
      this.orgCategoryDisabled = true
      getAction(this.url.getDeptInfo, { departCode: record.key }).then(res => {
        const data = res.result.data
        console.log(data.areaCode)
        if (data.areaCode === undefined) {
          data.areaCode = undefined
        }
        this.selectDeptInfo = data
      })
    },
    // 触发选中事件 勾选复选框
    onCheck (checkedKeys, info) {
      console.log('onCheck', checkedKeys, info)
      this.hiding = false
      // this.checkedKeys = checkedKeys.checked
      if (this.checkStrictly) {
        this.checkedKeys = checkedKeys.checked
      } else {
        this.checkedKeys = checkedKeys
      }
    },
    // 触发点击事件
    onSelect (selectedKeys, info) {
      this.$refs.ruleForm.resetFields()
      this.selectedKeys = selectedKeys
      const record = info.node.dataRef
      this.setValuesToForm(record)
      this.checkDeptName = record.title
    },
    // 编辑情况下，禁止选择当前节点及其子节点
    diGuiTreeEdit (item, vals) {
      const data = item
      const treeAry = []
      for (const i in data) {
        const v = data[i]
        const node = {}
        if (v === null || v === undefined) {
        } else {
          if (v.children && v.children.length > 0) {
            if (v.title.indexOf(vals) > -1) {
              node.class = 'k-tree-select'
              selectList.push(v.parentId)
            } else {
              node.class = ''
            }
            node.key = v.key
            node.title = v.title
            node.parentId = v.parentId
            node.children = this.diGuiTreeEdit(v.children, vals)
            treeAry.push(node)
          } else {
            if (v.title.indexOf(vals) > -1) {
              node.class = 'k-tree-select'
              selectList.push(v.parentId)
            } else {
              node.class = ''
            }
            node.key = v.key
            node.title = v.title
            node.parentId = v.parentId
            treeAry.push(node)
          }
        }
      }
      return treeAry
    },
    // 获取父节点
    getParents (checkKey) {
      for (var i = 0; i < this.departListSys.length; i++) {
        const tmp = this.departListSys[i]
        if (tmp.id === parseInt(checkKey)) {
          selectParentList.push(tmp.key)
          if (this.checkHasParent(tmp.parentId)) {
            this.getParents(tmp.parentId)
          }
        }
      }
    },
    // 检查是否有父节点
    checkHasParent (checkKey) {
      for (var i = 0; i < this.departListSys.length; i++) {
        const tmp = this.departListSys[i]
        if (tmp.id === checkKey) {
          return tmp.id
        }
      }
    },
    // 左侧检索
    onChange (e) {
      let value = e.target.value
      if (!value) {
        value = '@@@@'
      }
      selectList = []
      selectParentList = []
      this.departTree = this.diGuiTreeEdit(this.departTree, value)
      this.expandedKeys = []
      selectList.map(x => {
        this.getParents(x)
        selectParentList.map(x => {
          this.expandedKeys.push(x)
        })
      })
      if (this.expandedKeys.length === 0) {
        this.expandedKeys = expandedKeySource
      }
    },
    // 初始化数据 参数true为第一次，
    initData (firstFlag) {
      getAction(this.url.getDepartTree, {}).then(res => {
        if (firstFlag) {
          if (res.result.data[0].children) {
            const treeLv2 = res.result.data[0].children.map((item, index, arr) => {
              const treeLv2Tmp = (item.key)
              return treeLv2Tmp
            })
            this.expandedKeys = treeLv2
            expandedKeySource = treeLv2
          }
        }
        this.departTree = res.result.data
        this.getAllKeys(this.departTree)
      })
    },
    // 获取所有的key
    getAllKeys (node) {
      node.map((item, index, arr) => {
        this.allTreeKeys.push(item.key)
        const node = {}
        node.id = item.id
        node.key = item.key
        node.title = item.title
        node.parentId = item.parentId
        this.departListSys.push(node)
        if (item.children && item.children.length > 0) {
          this.getAllKeys(item.children)
        }
      })
    },
    // 右键点击下拉框改变事件
    dropStatus (visible) {
      if (visible === false) {
        this.dropTrigger = ''
      }
    },
    // 展开所有
    expandAll () {
      this.expandedKeys = this.allTreeKeys
    },
    // 关闭所有
    closeAll () {
      this.expandedKeys = []
    },
    // 全选
    checkALL () {
      this.checkedKeys = this.allTreeKeys
    },
    // 取消全选
    cancelCheckALL () {
      this.checkedKeys = []
    },
    // 添加
    handleAdd () {
      this.selectDeptInfo.parentId = undefined
      this.selectDeptInfo.parentName = ''
      this.orgCategoryDisabled = false
      this.selectDeptInfo.id = undefined
      this.checkDeptName = ''
      this.$refs.ruleForm.resetFields()

      this.selectDeptInfo.parentId = this.rightClickSelectedKey
      this.selectDeptInfo.parentName = this.rightClickSelectedName
      this.selectDeptInfo.address = ''
    },
    // 删除
    handleDelete () {
      getAction(this.url.departDel, { ids: this.rightClickSelectedKey }).then((resp) => {
        this.$message.success('删除成功!')
        this.initData(false)
      })
    },
    // 右键店家下拉关闭下拉框
    closeDrop () {
      this.dropTrigger = ''
    },
    // 右键操作方法
    rightHandle (node) {
      this.dropTrigger = 'contextmenu'
      this.rightClickSelectedKey = node.node.eventKey
      this.rightClickSelectedValue = node.node.value
      this.rightClickSelectedName = node.node.title
    }
  }
}
</script>
<style scoped>
.drawer-bootom-button {
  /*position: absolute;*/
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: left;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
</style>
